<?php

require "../utility.php";
require "./ac_utility.php";

function addAddrToDatabase(mysqli $conn, string $user_id, string $addr, string $is_default): bool {
    $is_default_bool = boolval($is_default);

    if ($is_default_bool) {
        // 保持唯一性
        if (!keepUnique($conn, $user_id)) {
            return false;
        }
    }

    $insert_str = "INSERT INTO Addr (userID, address, isDefault) VALUES(?, ?, ?);";
    $insert_stmt = $conn->prepare($insert_str);
    $insert_stmt->bind_param("isi", $user_id, $addr, $is_default_bool);
    $status = $insert_stmt->execute();
    return $status;
}

$addr_info_json = getJsonDataFromRawInput();
$conn = connect_mysql();
$user_id = getUserIdBySessionId($conn);

http_response_code(403);

if ($user_id !== null  &&
    check_keys($addr_info_json, "address", "default")) {
    $addr = $addr_info_json["address"];
    $is_default = $addr_info_json["default"];
    if (addAddrToDatabase($conn, $user_id, $addr, $is_default)) {
        // success
        http_response_code(200);
    }
}

$conn->close();

?>
